import { Request, Response, NextFunction } from 'express';
import _ from 'lodash';
import { getKitaps, getIdKitap, createKitap, getRecommend, updateKitap, deleteKitap, kitapStatusChange, createAuthorCon, byKeyWordSelect, getAudios, deleteKisim, countBook, createBolum, getByIdBolum, byBookIdGetBolum } from './kitap.service';
import { createMultisetMovie, updateMultisetMovie } from '../house/house.service';
import { reqGetFavorites } from '../favorites/favorites.service';

/**
 * 获取内容
 */
export const index = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  let pageNo = request.query.pageNo
  let pageSize = request.query.pageSize
  let status = request.query.status
  let type = request.query.categoryId
  let recommend = request.query.recommend
  let is_free = request.query.is_free
  let video_source = request.query.video_source
  let book_form = request.query.isLanguageTypeValue
  let keyWord = request.query.keyWord
  let bolum_id = request.query.bolum_id

  const data = await getKitaps(
    parseInt(`${pageNo}`, 10),
    parseInt(`${pageSize}`, 10),
    parseInt(`${type}`, 10),
    parseInt(`${status}`, 10),
    parseInt(`${recommend}`, 10),
    parseInt(`${is_free}`, 10),
    parseInt(`${video_source}`, 10),
    parseInt(`${book_form}`, 10),
    `${keyWord}`,
    parseInt(`${bolum_id}`, 10),
  );

  response.send(data);
}

/**
 * 获取推荐内容
 */
export const recommend = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {

  const data = await getRecommend();

  response.send(data);
}

/**
 * 获取内容(按 ID 查找)
 */
export const kitapDetail = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取内容 ID
  const { postId } = request.params;
  let user_id = request.user.id;

  // 调取内容
  try {
    const data = await getIdKitap(parseInt(postId, 10)); // 获取集
    const favorites = await reqGetFavorites(user_id, parseInt(postId, 10)); // 是否收藏
    const is_favorites = Array.isArray(favorites) ? favorites.length > 0 : false;
    data.is_favorites = is_favorites;

    // 做出响应
    response.send(data);
  } catch (error) {
    next(error);
  }
};

/**
 * 创建用户
 */
export const setAuthorCon = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取内容 ID
  const post = request.body;

  // 调取内容
  try {
    const data = await createAuthorCon(post);

    // 做出响应
    response.send(data);
  } catch (error) {
    next(error);
  }
};



/**
 * 按关键词搜索（模糊查询）
 */
export const selectByKey = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取关键词
  let { keyWord } = request.query;

  try {
    const data = await byKeyWordSelect(keyWord);
    response.send(data);
  } catch (error) {
    next(error);
  }
}

/**
 * 创建内容
 */
export const store = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取内容
  let kitapModel = request.body;
  let kisimModel = request.body.multisets; // قىسىم
  let bolumModel = request.body.bolumArr; // بۆلۈم
  delete kitapModel.multisets;
  delete kitapModel.bolumArr;
  let bolum_id = 0;

  // بۆلۈم بولسا بۆلۈم قوشىمىز
  if (bolumModel) {
    for(let e of bolumModel) {
      if(!e.id){
        let data = await createBolum(e);
        bolum_id = (data as any).insertId;
      }
      bolum_id = e.id;
    }
  }

  if (kitapModel.multiSet) {
    kisimModel = kitapModel.multiSet;
    delete kitapModel.multiSet;
  }
  let releaseTime = Math.floor(new Date().getTime())
  kitapModel.releaseTime = releaseTime;
  kisimModel.releaseTime = releaseTime;

  /* 创建 */
  if (kitapModel.id && kitapModel.id > 0) {
    
    const data = await updateKitap(kitapModel, parseInt(kitapModel.id, 10));;;

    // 创建多集内容
    for (let item of kisimModel) {
      item.book_id = kitapModel.id;
      item.bolum_id = bolum_id;;
      
      if (!item.id) {
        await createMultisetMovie(item);
      } else {
        await updateMultisetMovie(item, parseInt(item.id, 10))
      }
    };

    response.send(data);
  } else {
    const data = await createKitap(kitapModel);

    const bookId = (data as any).insertId;

    // 创建多集内容
    for (let item of kisimModel) {
      item.book_id = bookId;
      item.bolum_id = bolum_id;
      if (!item.id) {
        await createMultisetMovie(item);
      } else {
        await updateMultisetMovie(item, parseInt(item.id, 10))
      }
    };

    response.send(data);
  }

}

/**
 * 删除内容
 */
export const destroy = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取删除内容 ID
  const { postId } = request.params;

  // 删除
  try {
    const data = await deleteKitap(parseInt(postId, 10));
    response.send(data);
  } catch (error) {
    next(error);
  }
}

/**
 * 删除集
 */
export const destroyKisim = async (
  request: Request,
  response: Response,
  next: NextFunction
) => {
  // 获取删除内容 ID
  const { postId } = request.body;

  // 删除
  try {
    const data = await deleteKisim(parseInt(postId, 10));
    response.send(data);
  } catch (error) {
    next(error);
  }
}

/**
 * 状态
 */
export const status = async (
  request: Request,
  response: Response,
  next: NextFunction,
) => {
  // 获取内容 ID
  const postId = request.body.id;


  // 获取内容
  const post = _.pick(request.body, ['status']);

  // 执行
  try {
    const data = await kitapStatusChange(parseInt(postId, 10), post);
    response.send(data);
  } catch (error) {
    next(error);
  }
};

/**
 * 音频
 */
export const getAudio = async (
  request: Request,
  response: Response,
  next: NextFunction,
) => {
  // 获取内容 ID
  let bookId = request.query.bookId;
  let pageNo = request.query.pageNo;
  let pageSize = request.query.pageSize;
  let status = 1;
  let bolum = await byBookIdGetBolum(parseInt(`${bookId}`, 10));
  let bolum_id = bolum[0]?.id;

  // 执行
  try {
    const data = await getAudios(parseInt(`${bookId}`, 10), parseInt(`${pageSize}`, 10), parseInt(`${pageNo}`, 10), parseInt(`${status}`, 10), parseInt(`${bolum_id}`, 10));

    response.send(data);
  } catch (error) {
    next(error);
  }
};

/**
 * 统计书本 
 */
export const getTotalBook = async (
  request: Request,
  response: Response,
  next: NextFunction,
) => {
  // 执行
  try {
    const data = await countBook();

    response.send(data);
  } catch (error) {
    next(error);
  }
};

/**
 * بولۇم نۇمۇرى بلەن ئەسەرگە ئېرىشىش
 */
export const getBolumAudio = async (
  request: Request,
  response: Response,
  next: NextFunction,
) => {
  // 获取内容 ID
  let { bolum_id, book_id } = request.body;

  // 执行
  try {
    const data = await getByIdBolum(parseInt(`${bolum_id}`, 10), parseInt(`${book_id}`, 10));;

    response.send(data);
  } catch (error){ 
    next(error);
  }
  
}
